<script setup>
import { ref, computed } from 'vue'
import { Toast, ImagePreview, Dialog } from 'vant'
import { useRouter, useRoute } from 'vue-router'
import { storeToRefs } from 'pinia'

import { getCartTotalService, addCartService } from '@/api/cart'
import {
  getGoodsDetail,
  getGoodsService,
  getGoodsCommentListRows
} from '@/api/goods'
import CartCount from '@/components/CartCount.vue'
import { useUserStore } from '@/stores/user.js'

const route = useRoute()
const router = useRouter()

const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const isLogin = computed(() => Boolean(userInfo.value.token))

const total = ref(0)
const current = ref(0)
const detailObj = ref({})
const services = ref([])
const comment = ref({})
const show1 = ref(false)
const show2 = ref(false)
const seriveShow = ref(false)
const addCount = ref(1)

const imageNum = computed(() => {
  return detailObj.value.goods_images ? detailObj.value.goods_images.length : 0
})

const previewImage = (url) => {
  ImagePreview({ images: [url], showIndex: false })
}

const onChange = (index) => {
  current.value = index
}

const isFull = (socre, index) => {
  let max = 0
  if (socre === 30) {
    max = 1
  } else if (socre === 20) {
    max = 3
  } else {
    max = 5
  }
  return index <= max
}

const addCart = async () => {
  if (userInfo.value.token) {
    const {
      message,
      data: { cartTotal }
    } = await addCartService({
      goodsId: detailObj.value.goods_id,
      goodsSkuId: detailObj.value.skuList[0].goods_sku_id,
      goodsNum: addCount.value
    })
    show1.value = false
    Toast(message)
    total.value = cartTotal
  } else {
    Dialog.confirm({
      title: '温馨提示',
      message: '此时此刻需要您登录喔~',
      confirmButtonText: '去登录',
      cancelButtonText: '再逛会'
    })
      .then(() => {
        router.push('/login')
      })
      .catch(() => {})
  }
}
const buyNow = () => {
  if (userInfo.value.token) {
    router.push({
      path: '/checkout',
      query: {
        mode: 'buyNow',
        goodsId: detailObj.value.goods_id,
        goodsSkuId: detailObj.value.skuList[0].goods_sku_id,
        goodsNum: addCount.value
      }
    })
  } else {
    Dialog.confirm({
      title: '温馨提示',
      message: '此时此刻需要您登录喔~',
      confirmButtonText: '去登录',
      cancelButtonText: '再逛会'
    })
      .then(() => {
        router.push('/login')
      })
      .catch(() => {})
  }
}

const goSerive = () => {
  seriveShow.value = true
}

const goCart = () => {
  show1.value = true
}

const goBuy = () => {
  show2.value = true
}

const detailRef = ref(null)
const init = async () => {
  if (userInfo.value.token) {
    const {
      data: { cartTotal }
    } = await getCartTotalService()
    total.value = cartTotal
  }

  const goodsId = route.query.goodsId
  const {
    data: { detail }
  } = await getGoodsDetail(goodsId)

  detailObj.value = detail
  detailRef.value.innerHTML = detail.content.replaceAll(
    'width: 414px',
    'width: 375px'
  )

  const {
    data: { list }
  } = await getGoodsService(goodsId)
  services.value = list

  const { data } = await getGoodsCommentListRows(goodsId, 2)
  comment.value = data
}
init()
</script>

<template>
  <div class="detail">
    <van-nav-bar
      title="商品详情页"
      left-arrow
      fixed
      @click-left="$router.back()"
    />
    <van-swipe @change="onChange" :autoplay="1000" height="375" width="375">
      <van-swipe-item
        v-for="(item, index) in detailObj.goods_images"
        :key="index"
        ><img
          :src="item.preview_url"
          class="swipe-img"
          @click="previewImage(item.preview_url)"
      /></van-swipe-item>
      <template #indicator>
        <div class="custom-indicator">{{ current + 1 }}/{{ imageNum }}</div>
      </template>
    </van-swipe>

    <div class="goods-info">
      <p>
        <span>￥{{ detailObj.goods_price_min }}</span>
        <span>{{ detailObj.line_price_min }}</span>
        <span>已售{{ detailObj.goods_sales }}件</span>
      </p>
      <p>{{ detailObj.goods_name }}</p>
    </div>

    <div class="service-simple" @click="goSerive">
      <span class="left" v-for="item in services" :key="item.service_id"
        ><van-icon name="certificate" size="13" color="red" />{{
          item.name
        }}</span
      >
      <span class="right"><van-icon name="arrow" size="13" /></span>
    </div>

    <div class="goods-comment" v-if="comment.total">
      <p class="total">
        <span>商品评价（{{ comment.total }}条）</span>
        <span @click="$router.push(`/comment?goodsId=${$route.query.goodsId}`)"
          >查看更多<van-icon name="arrow" size="13"
        /></span>
      </p>
      <div class="list">
        <div class="item" v-for="item in comment.list" :key="item.comment_id">
          <p>
            <img v-if="item.user.avatar_url" :src="item.user.avatar_url" />
            <img v-else src="@/assets/default-avatar.png" />
            <span class="nickname">{{ item.user.nick_name }}</span>
            <span class="star">
              <span v-for="n in 5" :key="n">
                <van-icon
                  v-if="isFull(item.score, n)"
                  name="star"
                  size="16"
                  class="full"
                />
                <van-icon v-else name="star-o" size="16" class="blank" />
              </span>
            </span>
          </p>
          <p>{{ item.content }}</p>
          <p>{{ item.create_time }}</p>
        </div>
      </div>
    </div>

    <div class="content">
      <p class="content-title">商品描述</p>
      <div class="content-detail" ref="detailRef"></div>
    </div>

    <div class="bottom-bar">
      <div class="box" @click="$router.push('/home')">
        <van-icon name="home-o" size="22px" />
        <span>首页</span>
      </div>
      <div class="box" @click="$router.push('/cart')">
        <van-icon
          v-if="isLogin"
          name="shopping-cart-o"
          :badge="total ? total : null"
          size="22px"
        />
        <van-icon v-else name="shopping-cart-o" size="22px" />
        <span>购物车</span>
      </div>

      <button class="cart" @click="goCart">加入购物车</button>
      <button class="buy" @click="goBuy">立即购买</button>

      <!-- 购物车弹框 -->
      <van-popup
        v-model:show="show1"
        closeable
        close-icon="close"
        position="bottom"
        :style="{ height: '35%' }"
      >
        <div class="popup-header">
          <div class="left">
            <img :src="detailObj.goods_image" />
          </div>
          <div class="right">
            <p>￥{{ detailObj.goods_price_min }}</p>
            <p>库存：{{ detailObj.stock_total }}</p>
          </div>
        </div>
        <div class="popup-count">
          <span>数量</span>
          <CartCount
            :value="addCount"
            @input="
              (value) => {
                addCount = value
              }
            "
          ></CartCount>
        </div>
        <div class="popup-button">
          <button class="button1" @click="addCart" v-if="detailObj.stock_total">
            加入购物车
          </button>
          <button class="button1 disabled" v-else>该商品已抢完</button>
        </div>
      </van-popup>

      <!-- 立即购买弹框 -->
      <van-popup
        v-model:show="show2"
        closeable
        close-icon="close"
        position="bottom"
        :style="{ height: '35%' }"
      >
        <div class="popup-header">
          <div class="left">
            <img :src="detailObj.goods_image" />
          </div>
          <div class="right">
            <p>￥{{ detailObj.goods_price_min }}</p>
            <p>库存：{{ detailObj.stock_total }}</p>
          </div>
        </div>
        <div class="popup-count">
          <span>数量</span>
          <CartCount
            :value="addCount"
            @input="
              (value) => {
                addCount = value
              }
            "
          ></CartCount>
        </div>
        <div class="popup-button">
          <button class="button2" @click="buyNow" v-if="detailObj.stock_total">
            立即购买
          </button>
          <button class="button2 disabled" v-else>立即购买</button>
        </div>
      </van-popup>

      <!-- 服务弹框 -->
      <van-popup
        v-model:show="seriveShow"
        closeable
        position="bottom"
        :style="{ height: '35%' }"
      >
        <p class="popup-serice-header">服务</p>
        <div class="popup-service-content">
          <div class="item" v-for="item in services" :key="item.service_id">
            <van-icon name="certificate" size="14" color="red" />
            <div class="text">
              <p>{{ item.name }}</p>
              <p>{{ item.summary }}</p>
            </div>
          </div>
        </div>
      </van-popup>
    </div>
  </div>
</template>

<style lang="less" scoped>
.detail {
  padding-top: 46px;
  padding-bottom: 50px;
}

.disabled {
  background-color: rgb(204, 204, 204) !important;
}

.van-nav-bar {
  ::v-deep .van-nav-bar__title {
    font-weight: bold;
  }

  ::v-deep .van-icon-arrow-left {
    color: black;
  }
}

.custom-indicator {
  position: absolute;
  right: 20px;
  bottom: 30px;
  padding: 2px 5px;
  font-size: 13px;
  background: rgba(0, 0, 0, 0.1);
  color: #fff;
  border-radius: 10px;
}

.swipe-img {
  width: 375px;
  height: 375px;
}

.goods-info {
  width: 345px;
  height: 71px;
  padding: 12px 15px;
  margin-top: 12px;
  background-color: white;

  p:first-child {
    margin-bottom: 10px;

    span:first-child {
      color: #fa2209;
      margin-right: 7px;
      font-size: 21px;
    }

    span:nth-child(2) {
      font-size: 13px;
      text-decoration: line-through;
      color: #959595;
      margin-right: 105px;
    }

    span:last-child {
      font-size: 13px;
      color: #959595;
    }
  }

  p:last-child {
    font-size: 15px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box; /* 兼容旧版浏览器 */
    -webkit-line-clamp: 2; /* 显示两行 */
    -webkit-box-orient: vertical;
  }
}

.service-simple {
  width: 345px;
  height: 25px;
  padding: 5px 15px;
  background: transparent;
  font-size: 13px;
  line-height: 25px;

  .left {
    float: left;
    padding-right: 8px;
  }

  .right {
    float: right;
  }
}

.full {
  color: rgb(244, 162, 19);
}

.blank {
  color: rgb(178, 178, 178);
}

.goods-comment {
  background-color: white;
  width: 345px;
  // height: 236px;
  padding: 10px;
  margin-top: 12px;

  .total {
    display: flex;
    justify-content: space-between;
    align-content: center;
    font-size: 14px;

    span:first-child {
      color: #303133;
    }

    span:last-child {
      color: #999;

      .van-icon {
        margin-left: 5px;
      }
    }
  }

  .list {
    .item {
      width: 341px;
      height: 76px;
      padding: 7px 2px;
      border-bottom: 0.5px solid #f5f5f5;

      p {
        height: 25px;
        width: 100%;
        line-height: 25px;
      }

      p:first-child {
        display: flex;
        font-size: 12px;

        img {
          border-radius: 50%;
        }

        .nickname {
          padding: 0 5px;
        }

        .star {
          .van-icon {
            padding-right: 2px;
          }
        }
      }

      p:nth-child(2) {
        font-size: 13px;
        color: #333;
      }

      p:last-child {
        font-size: 12px;
        color: #999;
        margin-top: 5px;
      }
    }
  }
}

.content {
  .content-title {
    width: 345px;
    height: 19px;
    padding: 13px 15px;
    color: #303133;
    font-size: 14px;
  }

  .content-detail {
    padding: 0;
    width: 375px;
    max-width: 100%;

    img {
      display: block;
      max-width: 100% !important;
    }
  }
}

.bottom-bar {
  width: 100%;
  height: 53px;
  position: fixed;
  bottom: 0;
  left: 0;
  background-color: white;
  display: flex;
  justify-content: space-around;
  align-content: center;
  align-items: center;
  font-size: 11px;
  padding: 2px;

  .box {
    display: flex;
    flex-flow: column nowrap;
    justify-content: space-around;
    padding: 10px 0;
  }

  .cart {
    background: linear-gradient(90deg, #ffa600, #fb0);
    font-size: 14px;
    height: 36px;
    width: 123px;
    color: #fff;
    border-radius: 25px;
    border: none;
  }

  .buy {
    background: linear-gradient(90deg, #f9211c, #ff6335);
    font-size: 14px;
    height: 36px;
    width: 123px;
    color: #fff;
    border-radius: 25px;
    border: none;
  }
}

.van-popup {
  .popup-header {
    width: 351px;
    height: 90px;
    margin: 5px auto;
    margin-bottom: 20px;
    display: flex;

    .left {
      width: 90px;
      height: 90px;
      padding-right: 10px;

      img {
        width: 100%;
      }
    }

    .right {
      height: 90px;

      p:first-child {
        padding-top: 20px;
        color: rgb(254, 86, 10);
        font-size: 24px;
        padding-bottom: 20px;
      }

      p:last-child {
        font-size: 12px;
        color: #525252;
        padding-left: 5px;
      }
    }
  }

  .popup-count {
    width: 351px;
    height: 35px;
    margin: 0 auto;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;

    span:first-child {
      font-size: 14px;
    }
  }

  .popup-button {
    width: 351px;
    height: 40px;
    margin: 0 auto;

    button {
      width: 331px;
      height: 100%;
      margin: 0 auto;
      color: rgb(255, 255, 255);
      font-weight: 500;
      font-size: 14px;
      border: none;
      border-radius: 19px;
    }

    .button1 {
      background-color: rgb(255, 148, 2);
    }

    .button2 {
      background-color: rgb(254, 86, 10);
    }
  }

  .popup-serice-header {
    font-size: 15px;
    font-weight: bold;
    text-align: center;
    height: 20px;
    line-height: 20px;
    margin-bottom: 25px;
    margin-top: 12px;
  }

  .popup-service-content {
    padding: 12px;
    .item {
      display: flex;
      margin-bottom: 20px;

      .text {
        padding-left: 10px;
        width: 296px;
        height: 46px;

        p:first-child {
          color: #303133;
          font-size: 14px;
        }

        p:last-child {
          font-size: 13px;
          margin-top: 10px;
          color: #6d6d6d;
        }
      }
    }
  }
}
</style>
